package com.example.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * DataSourceConfig
 *
 * @author hao.chen
 * @date 2023/5/30 10:15
 */
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {

    public static final String DATA_SOURCE_NAME = "dataSource";
    public static final String TRANSACTION_MANAGER_NAME = "transactionManager";

    @Primary
    @Bean(name = DataSourceConfig.DATA_SOURCE_NAME, initMethod = "init", destroyMethod = "close")
    @ConfigurationProperties("spring.datasource.druid")
    public DruidDataSource dataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = DataSourceConfig.TRANSACTION_MANAGER_NAME)
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

}
